package com.softserveinc.appwidget;

import java.util.ArrayList;
import java.util.List;

import android.app.IntentService;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.util.Log;

import com.softserveinc.MovieManagerApplication;
import com.softserveinc.data.MovieDataManager;
import com.softserveinc.data.help.MovieListType;
import com.softserveinc.model.Movie;
import com.softserveinc.settings.AppWidgetSettingManager;
import com.softserveinc.settings.HardwareManager;

public class WidgetUpdateService extends IntentService {

	private static final String TAG = WidgetUpdateService.class.getSimpleName();

	private static final String NAME = WidgetUpdateService.class
			.getSimpleName();

	public WidgetUpdateService() {
		super(NAME);
	}

	@Override
	protected void onHandleIntent(final Intent intent) {
		try {

			int appWidgetId = intent.getIntExtra(
					AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);

			MovieManagerApplication application = (MovieManagerApplication) getApplicationContext();

			HardwareManager hardwareManager = application.getHardwareManager();

			if (!hardwareManager.isNetworkConnected()) {
				return;
			}

			MovieDataManager dataManager = application.getDataManager();
			AppWidgetSettingManager widgetSettingManager = application
					.getWidgetSettingManager();

			MovieListType listType = widgetSettingManager
					.getMovieListType(appWidgetId);

			int listSize = widgetSettingManager.getMovieSize(appWidgetId);

			ArrayList<Movie> movies = new ArrayList<Movie>();

			List<Movie> moviesFromDataManager = dataManager
					.getMovieList(listType);

			for (int i = 0; i < listSize; i++) {
				Movie movie = moviesFromDataManager.get(i);

				if (movie.getPoster() == null || movie.getPoster().isRecycled()) {
					dataManager.setPosterToMovie(movie);
				}

				movies.add(movie);
			}

			widgetSettingManager.updateCurrentMovieIndex(appWidgetId);

			Intent resultIntent = new Intent(
					MovieManagerWidgetProvider.APPWIDGET_UPDATE);

			resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
					appWidgetId);

			resultIntent.putExtra(
					MovieManagerWidgetProvider.APPWIDGET_DISPLAYED_MOVIE,
					movies);

			sendBroadcast(resultIntent);

		} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
		}
	}
}
